<template>
	<div class="kan-ban-container">
		<header class="header-box">
			<div class="header-left-box">
				<kan-ban-dropdown
					v-model="searchParams.workshopId"
					class="item-gap"
					:option-list="workshopList"
					@change="onSelectDropdown"
				></kan-ban-dropdown>
				<el-button :class="!isReview ? 'el-icon-view' : 'el-icon-edit'" class="edit-icon" type="primary" size="small" @click="isReview = !isReview">{{ isReview ? '设计' : '预览' }}</el-button>
				<el-button v-show="!isReview" class="el-icon-set-up edit-icon" type="primary" size="small" @click="drawer = !drawer">配置</el-button>
			</div>
			<div class="kan-ban-title">
				<div>{{ ruleForm.name }}</div>
				<el-popover title="标题" :append-to-body="false">
					<div style="width: 300px;">
						<div class="flex-start-center margin-top-10">
							<el-tag size="mini" class="item-gap" type="info">看板名称</el-tag>
							<jk-input v-model="ruleForm.name" placeholder="名称" size="small" class="width-100-percent"></jk-input>
						</div>
						<div class="flex-start-center margin-top-10">
							<el-tag size="mini" class="item-gap" type="info">定时刷新</el-tag>
							<el-checkbox v-model="ruleForm.openTimedRefresh" border size="small" @change="onCheckRefreshChange">开启</el-checkbox>
						</div>
						<div v-show="ruleForm.openTimedRefresh" class="flex-start-center margin-top-10 margin-bottom-10">
							<el-tag size="small" class="item-gap" type="info">时间间隔</el-tag>
							<el-input-number v-model="ruleForm.refreshTime" :min="1" size="small" class="width-100-percent"></el-input-number>
							<span>(秒)</span>
						</div>
					</div>
					<div v-show="!isReview" slot="reference" class="el-icon-edit edit-icon"></div>
				</el-popover>
			</div>
			<div class="header-right-box">
				<div class="current-time-bar">
					<div class="current-y-m">{{ currentTime.split(' ')[0] }}</div>
					<div class="current-h-m-s">{{ currentTime.split(' ')[1] }}</div>
				</div>
				<jk-full-screen-button class-name="kan-ban-container" size="small" class="item-gap"></jk-full-screen-button>
				<el-button v-show="!isReview" size="small" type="primary" icon="el-icon-s-open" class="item-gap" @click="onClearBtn"></el-button>
				<div><el-button size="small" :loading="refreshBtnLoading" type="primary" icon="el-icon-refresh" @click="onRefreshBtn"></el-button></div>
				<el-button v-show="!isReview" :loading="refreshBtnLoading" size="small" type="primary" icon="el-icon-position" style="margin-left: 4px;" @click="onSaveBtn"></el-button>
			</div>
		</header>
		<section class="section-box">
			<!--左-->
			<div class="section-column-item-left">
				<draggable v-model="leftChartList" :disabled="isReview" style="height: 100%;" :group="groupA" animation="300" drag-class="dragClass" ghost-class="ghostClass" chosen-class="chosenClass" @start="onStart" @end="onEnd">
					<transition-group class="" :style="isReview ? defaultStyle : leftStyle">
						<div v-for="(item, index) in leftChartList" :key="`k-${item.comName}`" class="section-column-item card-box-padding" :style="{cursor: !isReview ? 'move' : ''}">
							<div class="inner-card-box">
								<div class="card-title">
									<span>{{ item.title }}</span>
									<span v-show="!isReview" class="el-icon-delete delete-chart-icon" @click="onDeleteChartBtn('leftChartList', index)"></span>
									<!--<span v-show="isReview" class="chart-more" @click="onMoreBtn(item)">more</span>-->
								</div>
								<div class="card-chart">
									<component
										:is="item.comName"
										:workshop-id="searchParams.workshopId"
										location="bigScreen"
										:refresh-data="refresh"
										size="small"
									></component>
								</div>
							</div>
						</div>
					</transition-group>
				</draggable>
			</div>
			<!--中-->
			<div class="section-column-item-middle">
				<draggable v-model="middleTopChartList" :disabled="isReview" :group="groupD" class="section-column-item-middle_top" animation="300" drag-class="dragClass" ghost-class="ghostClass" chosen-class="chosenClass" @start="onStart" @end="onEnd">
					<transition-group class="" :style="isReview ? defaultStyle : middleTopStyle">
						<div v-for="(item, index) in middleTopChartList" :key="`k-${item.comName}`" style="height: 100%;" class="card-box-padding" :style="{cursor: !isReview ? 'move' : ''}">
							<div class="inner-card-box">
								<div class="card-title">
									<span>{{ item.title }}</span>
									<span v-show="!isReview" class="el-icon-delete delete-chart-icon" @click="onDeleteChartBtn('middleTopChartList', index)"></span>
									<!--<span v-show="isReview" class="chart-more" @click="onMoreBtn(item)">more</span>-->
								</div>
								<div class="card-chart">
									<component
										:is="item.comName"
										:workshop-id="searchParams.workshopId"
										location="bigScreen"
										:data-id="item.intelliReportId"
										:refresh-data="refresh"
										size="small"
									></component>
								</div>
							</div>
						</div>
					</transition-group>
				</draggable>
				<draggable v-model="middleBottomChartList" :disabled="isReview" :group="groupC" style="height: 33.333333%;" animation="300" drag-class="dragClass" ghost-class="ghostClass" chosen-class="chosenClass" @start="onStart" @end="onEnd">
					<transition-group class="" :style="isReview ? defaultStyle : middleBottomStyle">
						<div v-for="(item, index) in middleBottomChartList" :key="`k-${item.comName}`" style="height: 100%;" class="card-box-padding" :style="{cursor: !isReview ? 'move' : ''}">
							<div class="inner-card-box">
								<div class="card-title">
									<span>{{ item.title }}</span>
									<span v-show="!isReview" class="el-icon-delete delete-chart-icon" @click="onDeleteChartBtn('middleBottomChartList', index)"></span>
									<!--<span v-show="isReview" class="chart-more" @click="onMoreBtn(item)">more</span>-->
								</div>
								<div class="card-chart">
									<component
										:is="item.comName"
										:workshop-id="searchParams.workshopId"
										location="bigScreen"
										:data-id="item.intelliReportId"
										:refresh-data="refresh"
										size="small"
									></component>
								</div>
							</div>
						</div>
					</transition-group>
				</draggable>
			</div>
			<!--右-->
			<div class="section-column-item-right">
				<draggable v-model="rightChartList" :disabled="isReview" style="height: 100%;" :group="groupB" animation="300" drag-class="dragClass" ghost-class="ghostClass" chosen-class="chosenClass" @start="onStart" @end="onEnd">
					<transition-group class="" :style="isReview ? defaultStyle : rightStyle">
						<div v-for="(item, index) in rightChartList" :key="`k-${item.comName}`" class="section-column-item card-box-padding" :style="{cursor: !isReview ? 'move' : ''}">
							<div class="inner-card-box">
								<div class="card-title">
									<span>{{ item.title }}</span>
									<span v-show="!isReview" class="el-icon-delete delete-chart-icon" @click="onDeleteChartBtn('rightChartList', index)"></span>
									<!--<span v-show="isReview" class="chart-more" @click="onMoreBtn(item)">more</span>-->
								</div>
								<div class="card-chart">
									<component
										:is="item.comName"
										:workshop-id="searchParams.workshopId"
										location="bigScreen"
										:data-id="item.intelliReportId"
										:refresh-data="refresh"
										size="small"
									></component>
								</div>
							</div>
						</div>
					</transition-group>
				</draggable>
			</div>
		</section>
		<drawer
			title="图表"
			width="500px"
			:drawer-state="drawer"
			:direction="direction"
			:show-confirm-btn="false"
			cancel-btn-text="关闭"
			cancel-btn-type="danger"
			@on-visible-change="onVisibleChangeOfDrawer"
		>
			<div class="flex-center margin-bottom-10">
				<el-radio-group v-model="direction" size="small">
					<el-radio-button label="left">
						<span class="el-icon-back"></span>
						<span>左侧</span>
					</el-radio-button>
					<el-radio-button label="right">
						<span class="el-icon-right"></span>
						<span>右侧</span>
					</el-radio-button>
				</el-radio-group>
			</div>
			<div style="">
				<draggable v-model="optionalChartList" style="width: 100%;height: 100%;box-sizing: border-box;" :group="groupE" animation="300" drag-class="dragClass" ghost-class="ghostClass" chosen-class="chosenClass" @start="onStart" @end="onEnd">
					<transition-group class="">
						<div
							v-for="(item, idx) in optionalChartList"
							:key="`s-${item.comName}`"
							class="template-chart"
						>
							<div class="text-center margin-bottom-10">
								<span>{{ idx + 1 }}、{{ item.title }}</span>
							</div>
							<component
								:is="item.comName"
								style="height: 240px;"
								:refresh-data="refresh"
								:workshop-id="searchParams.workshopId"
							></component>
						</div>
					</transition-group>
				</draggable>
			</div>
		</drawer>
	</div>
</template>

<script>
    import { formatTime } from '@/utils/jk/jk-tool';
    import draggable from 'vuedraggable';
    import drawer from './componenst/drawer/index';
    import kanBanDropdown from './componenst/kan-ban-dropdown';
    import scheduleShiftProductionChart from './componenst/charts/schedule-shift-production-chart';
    import productProductionChart from './componenst/charts/product-production-chart';
    import machineRealTime from './componenst/charts/machine-real-time';
    import middleChart from './componenst/charts/middle-chart';
    import machineProductionRanking from './componenst/charts/machine-production-ranking';
    import machineEfficiencyRanking from './componenst/charts/machine-efficiency-ranking';
    import machineStopTimeRanking from './componenst/charts/machine-stop-time-ranking';
    import machineDoffTimeRanking from './componenst/charts/machine-doff-time-ranking';
    import orderProgressRanking from './componenst/charts/order-progress-ranking';
    import { reportProductionHomeLayoutGet, reportProductionHomeLayoutUpdate } from '../../../api/production/kanBan';
    import { tipsBar } from '../../../utils/jk/jk-tool';
    import processOpenNum from './componenst/charts/process-open-num';
    import processScheduleShiftQtyChart from './componenst/charts/process-schedule-shift-qty';
    import processCurrentMonthQtyChart from './componenst/charts/process-current-month-qty';
    import floorTemHumChart from './componenst/charts/floor-tem-hum';
    import allWorkshopMiddleChart from './componenst/charts/all-workshop-middle-chart';
    import ltRealTimeQty from './componenst/charts/lt-real-time-qty';
    import currentScheduleShiftProcessMachineYieldEnergy from './componenst/charts/currentScheduleShiftProcessMachineYieldEnergy/index';
    import currentScheduleShiftProcessEmpNum from './componenst/charts/current-schedule-shift-process-emp-num';
    import { systemWorkshopPage } from '../../../api/basicData/workshop';
    export default {
        components: {
            currentScheduleShiftProcessEmpNum,
            currentScheduleShiftProcessMachineYieldEnergy,
            ltRealTimeQty,
            allWorkshopMiddleChart,
            floorTemHumChart,
            processCurrentMonthQtyChart,
            processScheduleShiftQtyChart,
            processOpenNum,
            orderProgressRanking,
            machineDoffTimeRanking,
            machineStopTimeRanking,
            machineEfficiencyRanking,
            middleChart,
            machineProductionRanking,
            scheduleShiftProductionChart,
            productProductionChart,
            machineRealTime,
            kanBanDropdown,
            drawer,
            draggable
        },
        data() {
            return {
                refreshTimer: null,
                refreshBtnLoading: false,
                isReview: true,
                dataId: null,
                direction: 'right',
                defaultStyle: 'height: 100%;display: block;box-sizing: border-box;overflow: auto;',
                leftStyle: 'height: 100%;display: block;box-sizing: border-box;overflow: auto;border: solid 1px #2b5790;border-right:none;',
                rightStyle: 'height: 100%;display: block;box-sizing: border-box;overflow: auto;border: solid 1px #2b5790;border-left:none;',
                middleTopStyle: 'height: 100%;display: block;box-sizing: border-box;overflow: auto;border-top: solid 1px #2b5790;border-left: solid 1px #2b5790;border-right: solid 1px #2b5790;',
                middleBottomStyle: 'height: 100%;display: block;box-sizing: border-box;overflow: auto;border: solid 1px #2b5790;',
                leftChartList: [],
                rightChartList: [],
                middleBottomChartList: [],
                middleTopChartList: [],
                groupA: { name: 'itxst', put: true },
                groupB: { name: 'itxst', put: true },
                groupC: { name: 'itxst', put: true, pull: true },
                groupD: { name: 'itxst', put: true },
                groupE: { name: 'itxst', put: false, pull: 'clone' },
                refresh: 0,
                tableLoading: false,
                drawer: false,
                timer: {},
                currentTime: '',
                isFullScreen: true,
                optionalChartList: [],
                chartList: [
                    { title: '当班工序挡车人员统计', comName: 'currentScheduleShiftProcessEmpNum' },
                    { title: '当班工序机台产能监控', comName: 'currentScheduleShiftProcessMachineYieldEnergy' },
                    { title: '络筒机台实时监控', comName: 'ltRealTimeQty' },
                    { title: '生产概况(细纱)', comName: 'allWorkshopMiddleChart' },
                    { title: '区域温湿度监控', comName: 'floorTemHumChart' },
                    { title: '工序本月产量', comName: 'processCurrentMonthQtyChart' },
                    { title: '工序当班实时产量', comName: 'processScheduleShiftQtyChart' },
                    { title: '工序实时开台数', comName: 'processOpenNum' },
                    { title: '机台实时数据', comName: 'machineRealTime' },
                    // { title: '当班生产数据(细纱)', comName: 'middleChart' },
                    { title: '最近班次产量及盈亏', comName: 'scheduleShiftProductionChart' },
                    { title: '机台落纱时长排行', comName: 'machineDoffTimeRanking' },
                    { title: '当班品种产量及盈亏', comName: 'productProductionChart' },
                    { title: '当班机台效率排行', comName: 'machineEfficiencyRanking' },
                    { title: '当班机台停机时长排行', comName: 'machineStopTimeRanking' },
                    { title: '当班品种机台产量排行', comName: 'machineProductionRanking' },
                    { title: '订单生产进度', comName: 'orderProgressRanking' }
                ],
                workshopList: [],
                tooltipState: false,
                ruleForm: {
                    openTimedRefresh: false,
                    refreshTime: 0,
                    name: '生产管理驾驶舱',
                    workshopId: null,
                    workshopCode: '',
                    workshopName: null
                },
                searchParams: {
                    workshopId: null,
                    customerName: '',
                    selectOpen: true
                },
                openRefresh: false
            };
        },
        methods: {
            getOptionalChart() {
                const arr = [
                    ...this.leftChartList,
                    ...this.rightChartList,
                    ...this.middleTopChartList,
                    ...this.middleBottomChartList
                ];
                this.optionalChartList = this.chartList.filter(x => !arr.map(x => x.comName).includes(x.comName));
            },
            onMoreBtn() {
                tipsBar(this, 'custom', 'success', '开发中,敬请期待!');
            },
            onSelectDropdown(e) {
                this.refresh = Math.random();
                this.$set(this.searchParams, 'workshopId', e);
                this.getKanBanLayoutRequest();
            },
            onRun() {
                clearInterval(this.refreshTimer);
                if (this.ruleForm.openTimedRefresh && this.ruleForm.refreshTime) {
                    this.refreshTimer = setInterval(() => {
                        this.refresh = Math.random();
                    }, this.ruleForm.refreshTime * 1000);
                }
            },
            onCheckRefreshChange() {
                this.ruleForm.refreshTime = 6;
            },
            onRefreshBtn() {
                this.refreshBtnLoading = true;
                this.getKanBanLayoutRequest();
            },
            onDeleteChartBtn(e, index) {
                this[e].splice(index, 1);
                this.getOptionalChart();
            },
            onClearBtn() {
                this.leftChartList = [];
                this.rightChartList = [];
                this.middleTopChartList = [];
                this.middleBottomChartList = [];
            },
            onConfirmBtnOfPopover(e) {
                this.drawer = true;
                this.direction = e;
            },
            onVisibleChangeOfDrawer(e) {
                this.drawer = e;
            },
            onSaveBtn() {
                if (this.ruleForm.name) {
                    this.saveRequest();
                } else {
                    this.$tipsBar(this, 'custom', 'error', '请填写看板名称！');
                }
            },
            setParams() {
                const item = {
                    name: this.ruleForm.name,
                    refreshTime: this.ruleForm.refreshTime,
                    openTimedRefresh: this.ruleForm.openTimedRefresh
                };
                item.leftChartList = JSON.parse(JSON.stringify(this.leftChartList));
                item.rightChartList = JSON.parse(JSON.stringify(this.rightChartList));
                item.middleTopChartList = JSON.parse(JSON.stringify(this.middleTopChartList));
                item.middleBottomChartList = JSON.parse(JSON.stringify(this.middleBottomChartList));
                return JSON.stringify(item);
            },
            saveRequest() {
                const jsonStr = this.setParams();

                return reportProductionHomeLayoutUpdate({
                    workshopId: this.searchParams.workshopId,
                    configValue: jsonStr
                }).then(res => {
                    if (res.data.status === 200) {
                        tipsBar(this, 'save');
                        this.getDependentData();
                    }
                });
            },
            onStart() {
                this.drag = true;
            },
            onEnd() {
                this.drag = false;
                this.getOptionalChart();
            },
            handleClose() {
                this.drawer = false;
            },
            getCurrentTime() {
                this.currentTime = formatTime(Date.now());
                this.timer = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getCurrentTime();
                    this.isReview = Number(this.$route.query.isReview);
                    this.dataId = this.$route.query.id;
                    this.getDependentData();
                });
            },
            getKanBanLayoutRequest() {
                if (this.searchParams.workshopId) {
                    this.refreshBtnLoading = true;
                    return reportProductionHomeLayoutGet({
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        this.refreshBtnLoading = false;
                        if (res.data.status === 200) {
                            if (res.data.res) {
                                const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                                resData.configValue = resData.configValue ? JSON.parse(resData.configValue) : {};
                                this.$set(this.ruleForm, 'name', resData.configValue.name);
                                this.$set(this.ruleForm, 'refreshTime', resData.configValue.refreshTime);
                                this.$set(this.ruleForm, 'openTimedRefresh', resData.configValue.openTimedRefresh);
                                this.leftChartList = resData.configValue.leftChartList;
                                this.rightChartList = resData.configValue.rightChartList;
                                this.middleTopChartList = resData.configValue.middleTopChartList;
                                this.middleBottomChartList = resData.configValue.middleBottomChartList;
                            } else {
                                this.$set(this.ruleForm, 'name', '');
                                this.$set(this.ruleForm, 'refreshTime', '');
                                this.$set(this.ruleForm, 'openTimedRefresh', false);
                                this.leftChartList = [];
                                this.rightChartList = [];
                                this.middleTopChartList = [];
                                this.middleBottomChartList = [];
                            }
                            this.getOptionalChart();
                            this.onRun();
                        }
                    });
                }
            },
            getWorkshopListRequest() {
                return systemWorkshopPage({
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.workshopList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.contentLoading = true;
                await this.getWorkshopListRequest();
                if (this.searchParams.workshopId) await this.getKanBanLayoutRequest();
                this.contentLoading = false;
            }

        },
        mounted() {
            // this.isReview = Number(this.$route.query.isReview);
            this.dataId = this.$route.query.id;
            this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.getDependentData();
            this.getCurrentTime();
        },
        beforeRouteLeave(to, from, next) {
            clearInterval(this.timer);
            clearInterval(this.refreshTimer);
            next();
        },
        beforeRouteEnter(from, to, next) {
            next((_this) => {
                _this.onRun();
                _this.getCurrentTime();
            });
        }
    };
</script>

<style scoped lang="scss">
    @import "./layout";
</style>
